package com.epalmpay.service.management.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONObject;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.bonus.BonusAdjustbatchInDTO;
import com.epalmpay.entity.Group;
import com.epalmpay.mapper.GroupMapper;
import com.epalmpay.mapper.UserbaseMapper;
import com.epalmpay.util.Const;
import com.epalmpay.util.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.epalmpay.config.Global;
import com.epalmpay.dto.system.UserInDTO;
import com.epalmpay.dto.system.UserOutDTO;
import com.epalmpay.entity.Agent;
import com.epalmpay.entity.Shop;
import com.epalmpay.entity.Userbase;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum;
import com.epalmpay.mapper.AgentMapper;
import com.epalmpay.mapper.ShopMapper;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.management.IUserService;

@Service("userService") 
public class UserServiceImpl implements IUserService {
	
	@Resource  
    private UserbaseMapper userbaseMapper;
	@Resource  
    private AgentMapper agentMapper;
	@Resource  
	private ShopMapper shopMapper;
	@Autowired
	@Lazy
	private ITemplateMailSendService templateMailSendService;
	@Resource
	private GroupMapper groupMapper;
	
	/**登录判断
	 * @return
	 * @throws Exception
	 */
	public List<Userbase> getUserByNameAndPwd(Userbase user)throws Exception{
		List<Userbase> userlist=userbaseMapper.findUserList(user);
		return userlist;
	}
	
	
	/**通过用户ID获取用户信息和角色信息
	 * @return
	 * @throws Exception
	 */
	public Userbase getUserAndRoleById(Long userId) throws Exception {
		return userbaseMapper.selectUserAndRoleById(userId);
	}
	
	
	/**列出某角色下的所有用户
	 * @return
	 * @throws Exception
	 */
	public List<Userbase> listAllUserByRoldId(String userId) throws Exception {
		return userbaseMapper.listAllUserByRoldId(userId);
		
	}
	
	
	/**用户列表分页
	 * @return
	 * @throws Exception
	 */
	public List<Userbase> listUsers(Userbase user)throws Exception{
		return userbaseMapper.UserslistPage(user); 
	}
	
	/**用户列表分页
	 * @return
	 * @throws Exception
	 */
	public List<Userbase> listZfUsers(Userbase user)throws Exception{
		return userbaseMapper.UsersZflistPage(user); 
	}
	
	/**数据校验
	 * @return
	 * @throws Exception
	 */
	public Userbase has(Userbase user)throws Exception{
		return userbaseMapper.has(user);
	}


	@Override
	public int ifHas(Userbase user) throws Exception {
		return userbaseMapper.ifHas(user);
	}

	@Override
	public void updateStatus(Userbase userbase) {
		userbaseMapper.updateByPrimaryKeySelective(userbase);
	}



	/**通过id获取数据
	 * @return
	 * @throws Exception
	 */
	public Userbase findById(Userbase user)throws Exception{
		return userbaseMapper.selectUserAndRoleById(user.getId()); 
	}
	
	/**保存用户
	 * @throws Exception
	 */
	public void saveU(Userbase user)throws Exception{
		Userbase userbase = userbaseMapper.selectUserName(user.getUsername());
		if(userbase != null){
			throw new ApplicationException("用户名:" + user.getUsername() + "已经存在！");
		}
		userbaseMapper.insert(user);
	}
	 
	/**修改用户
	 * @throws Exception
	 */
	public void editUser(Userbase user)throws Exception{
		userbaseMapper.updateByPrimaryKey(user);
	}
	
	/**删除用户
	 * @throws Exception
	 */
	public void deleteU(Userbase user)throws Exception{
		userbaseMapper.deleteByPrimaryKey(user.getId()); 
	}
	
	public Userbase findByUsername(String userName) throws Exception {
		// TODO Auto-generated method stub
		return userbaseMapper.selectUserName(userName);
	}
		
	/***
	 * 查询销售用户列表
	 * @return
	 * @throws Exception
	 */
	public List<UserOutDTO> getDevelopeUserList() throws Exception{
		
		List<Userbase> developeUserList = userbaseMapper.listAllUserByRoldId(Global.SALEMAN_ROLEID);
		//List<Userbase> developeUserList = userbaseMapper.listAllUserByRoldId("6c937bf8978041f687b1e63fa05cdd90");
		List<UserOutDTO> userOutDTOList = new ArrayList<UserOutDTO>();
		
		for (Userbase developeUser : developeUserList) {
			UserOutDTO userOutDTO = new UserOutDTO();
			userOutDTO.setId(developeUser.getId());
			userOutDTO.setUsername(developeUser.getUsername());
			userOutDTOList.add(userOutDTO);
		}
		if(userOutDTOList.size()==0)
			userOutDTOList = null;
		
		return userOutDTOList;
	}


	@Override
	public void updateLoginPassword(Userbase member,String rootHomeUrl) {
		userbaseMapper.updateByPrimaryKeySelective(member);
		try {
			templateMailSendService.sendMemberTemplate(member.getId(), BizEnum.WebTemplateType.template14.getType(), rootHomeUrl,"登录");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public UserOutDTO shopOrAgent(UserInDTO userIn) throws Exception {
		UserOutDTO userOutDTO=new UserOutDTO();
		if(userIn.getUserType().equals(CommonEnum.UserType.Store.getType())){
			Shop shop=shopMapper.selectUserId(userIn.getUserId());
			if(shop!=null){
				userOutDTO.setShopId(shop.getId());
				userOutDTO.setShopName(shop.getMerchantName());
				userOutDTO.setAgentId(shop.getShopGroupRelation().getAgentId());
			}
		}else if(userIn.getUserType().equals(CommonEnum.UserType.Agents.getType())){
			Agent agent=agentMapper.selectUserId(userIn.getUserId());
			if(agent!=null){
				userOutDTO.setAgentId(agent.getId());
				userOutDTO.setAgentLevel(agent.getAgentLevel()); 
				userOutDTO.setAgentName(agent.getMerchantName()); 
			}
		}
		return userOutDTO;
	}

	@Override
	public List<Userbase> queryOperatorList(BonusAdjustbatchInDTO bonusAdjustbatchInDTO) {
		return userbaseMapper.queryOperatorList(bonusAdjustbatchInDTO);
	}

	@Override
	public UserOutDTO queryLoginNameByPhoneAndName(UserInDTO userInDTO) throws Exception {
		Userbase userbase = userbaseMapper.queryUserType(userInDTO);
		if(userbase==null){
			throw new ApplicationException("账户名不存在");
		}
		userInDTO.setUserType(userbase.getUserType());
		UserOutDTO userOutDTO = userbaseMapper.queryDataByNameAndPhone(userInDTO);
		if(userOutDTO.getTotalCount() !=1){
			throw new ApplicationException("开户账户预留手机号不匹配(不是开户人无法修改)");
		}
		return userOutDTO;
	}


	@Override
	public UserOutDTO queryDataByNameAndPhone(UserInDTO userInDTO) throws Exception {
		UserOutDTO userOutDTO = new UserOutDTO();
		Userbase userbase2 = userbaseMapper.queryUserType(userInDTO);
//		if(userbase==null){
//			throw new ApplicationException("账户名不存在");
//		}
//		userInDTO.setUserType(userbase.getUserType());
//		UserOutDTO userOutDTO = userbaseMapper.queryDataByNameAndPhone(userInDTO);
//		if(userOutDTO.getTotalCount() !=1){
//			throw new ApplicationException("开户账户预留手机号不匹配(不是开户人无法修改)");
//		}

//		Userbase userbase2 = new Userbase();
		userbase2.setId(userbase2.getId());
		userbase2.setGmtModified(new Date());
		userbase2.setPassword(new SimpleHash("SHA-1", userInDTO.getUsername(), userInDTO.getPassword()).toString());
		userbaseMapper.updateByPrimaryKeySelective(userbase2);
		return userOutDTO;
	}

	@Override
	public UserOutDTO queryGroupOrAgentInfo(UserInDTO userInDTO) throws Exception {
		return userbaseMapper.queryGroupOrAgentInfo(userInDTO);
	}

	@Override
	public void updateUserInfo(UserInDTO userInDTO) throws Exception {
		if(userInDTO.getUserType()==1){
			Group group = new Group();
			group.setId(userInDTO.getId());
			group.setMerchantName(userInDTO.getGroupName());
			group.setAddress(userInDTO.getAddress());
			group.setPrincipal(userInDTO.getPrincipal());
			group.setPrincipalMobile(userInDTO.getPrincipalMobile());
			group.setGmtModified(new Date());
			groupMapper.updateByPrimaryKeySelective(group);
		}
		if(userInDTO.getUserType()==2){

		}
		if(userInDTO.getUserType()==3){
			Userbase userbase= new Userbase();
			userbase.setId(userInDTO.getId());
			userbase.setName(userInDTO.getName());
			userbase.setPhone(userInDTO.getPhone());
			userbase.setGmtModified(new Date());
			userbaseMapper.updateByPrimaryKeySelective(userbase);
		}
		if(userInDTO.getUserType()==4){
			Agent agent = new Agent();
			agent.setId(userInDTO.getId());
			agent.setPrincipal(userInDTO.getPrincipal());
			agent.setPrincipalMobile(userInDTO.getPrincipalMobile());
			agent.setManageAddress(userInDTO.getManageAddress());
			agent.setMemo(userInDTO.getMemo());
			if(StringUtils.isNotBlank(userInDTO.getProvinceCityDistrict())){
				String[] addressdistct=userInDTO.getProvinceCityDistrict().split("/");
				if(addressdistct.length>0){
					if(addressdistct.length>0){
						agent.setAddressProvince(addressdistct[0]);
					}
					if(addressdistct.length>1){
						agent.setAddressCity(addressdistct[1]);
					}
					if(addressdistct.length>2){
						agent.setAddressDistrict(addressdistct[2]);
					}
				}
			}
			agent.setGmtModified(new Date());
			agentMapper.updateByPrimaryKeySelective(agent);

		}
		if(userInDTO.getUserType()==5){
			Shop shop = new Shop();
			shop.setId(userInDTO.getId());
			shop.setPrincipalName(userInDTO.getPrincipalName());
			shop.setPrincipalMobile(userInDTO.getPrincipalMobile());
			shop.setMemo(userInDTO.getMemo());
			if(StringUtils.isNotBlank(userInDTO.getProvinceCityDistrict())){
				String[] addressdistct=userInDTO.getProvinceCityDistrict().split("/");
				if(addressdistct.length>0){
					if(addressdistct.length>0){
						shop.setAddressProvince(addressdistct[0]);
					}
					if(addressdistct.length>1){
						shop.setAddressCity(addressdistct[1]);
					}
					if(addressdistct.length>2){
						shop.setAddressDistrict(addressdistct[2]);
					}
				}
			}
			shop.setAddress(userInDTO.getAddress());
			//根据地址解析金纬度
			String detailed=userInDTO.getProvinceCityDistrict()+userInDTO.getAddress();
			String result= HttpClientUtil.get(Const.GEOCODER+"?="+detailed+"&key="+Const.MAP_KEY);
			JSONObject jsonObj=JSONObject.parseObject(result);
			Object statusObject=jsonObj.get("status");
			Integer status=Integer.parseInt(String.valueOf(statusObject));
			if(!status.equals(0)){
				throw new ApplicationException(Rescode.FAIL,"地理位置解析异常,请检查区域管理地址的填写");
			}
			JSONObject resultObject=jsonObj.getJSONObject("result");
//			String title=resultObject.getString("title");
//			JSONObject address_componentsObject=resultObject.getJSONObject("address_components");//地址详细信息
			JSONObject locationObject=resultObject.getJSONObject("location");//经纬度对象

			String lng=locationObject.getString("lng")+"";
			String lat=locationObject.getString("lat")+"";

			shop.setLongitude(lng);
			shop.setLatitude(lat);

			shop.setGmtModified(new Date());
			shopMapper.updateByPrimaryKeySelective(shop);
		}
	}


}
